package com.iwechat.security.coder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iwechat.security.SecurityCoder;
import com.iwechat.util.DataUtil;

public class RSACoderSuport extends SecurityCoder {
    private static final Logger         logger        = LoggerFactory.getLogger(RSACoderSuport.class);
    private static final RSACoderSuport suport        = new RSACoderSuport();
    private static final String         RSA_KEY_STORE = "keyStore";
    private String                      keyPath;
    private KeyPair                     keyPair;

    private RSACoderSuport() {
        this.keyPair = this.initKey(null);
        logger.info("### " + this + " init succeed!");
    }

    public static RSACoderSuport getSuport() {
        return suport;
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     *
     * @return base64String
     * @throws Exception
     */
    public String signB64(byte[] data) throws Exception {
        return Base64.encodeBase64String(sign(data));
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data
     *            加密数据
     *
     * @return
     * @throws Exception
     */
    public byte[] sign(byte[] data) throws Exception {
        return RSACoder.sign(data, this.keyPair.getPrivate());
    }

    /**
     * 校验数字签名
     *
     * @param data
     *            加密数据
     * @param publicKey
     *            公钥
     * @param sign
     *            数字签名
     *
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     *
     */
    public boolean verify(byte[] data, String publicKey, byte[] sign) throws Exception {
        return RSACoder.verify(data, publicKey, sign);
    }

    /**
     * 私钥解密
     *
     * @param data
     *            待解密数据
     * @return byte[] 解密数据
     * @throws Exception
     */
    public byte[] decryptByPrivateKey(byte[] data) throws Exception {
        return RSACoder.decryptByPrivateKey(data, this.keyPair.getPrivate());
    }

    /**
     * 公钥加密
     *
     * @param data
     *            待加密数据
     * @param publicKey
     *            公钥
     * @return byte[] 加密数据
     * @throws Exception
     */
    public byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        return RSACoder.encryptByPublicKey(data, publicKey);
    }

    /**
     * 初始化密钥<br>
     *
     * @param path
     *            制定路径下生成密钥
     * @return
     * @throws Exception
     */
    public KeyPair initKey(String path) {
        if (path == null) {
            this.keyPath = DataUtil.getConfigPath(RSA_KEY_STORE);
        } else {
            this.keyPath = path;
        }
        this.keyPath = this.keyPath + File.separator + "keypair.rsa";
        File keyStore = new File(this.keyPath);
        KeyPair keyPair = null;
        try {
            if (keyStore.exists()) {
                keyPair = this.readKeyPair();
            } else {
                keyPair = this.genKeyPair();
            }
            String publickB64 = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
            logger.info("keyPath:\t" + keyPath);
            logger.info("publickKey_b64:\t" + publickB64);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return keyPair;
    }

    /**
     * 生成新key
     *
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    private KeyPair genKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSACoder.KEY_ALGORITHM);
        keyPairGen.initialize(RSACoder.KEY_SIZE);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        this.saveKeyPair(keyPair);
        return keyPair;
    }

    /**
     * 获取密钥对
     *
     * @return
     */
    private KeyPair readKeyPair() {
        KeyPair kp = null;
        ObjectInputStream ois = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(this.keyPath);
            ois = new ObjectInputStream(fis);
            kp = (KeyPair) ois.readObject();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
        return kp;
    }

    /**
     * 保存keyPair
     *
     * @param keyPair
     */
    private void saveKeyPair(KeyPair keyPair) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(this.keyPath);
            oos = new ObjectOutputStream(fos);
            // 生成密钥
            oos.writeObject(keyPair);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
